import React from 'react'
import PropTypes from 'prop-types'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import { ListMenuType } from 'utils/enums'
import { config } from 'utils'
import { Row, Col, Button, Popconfirm, Modal } from 'antd'
import { List, Page, ChooseModal } from 'components'
import queryString from 'query-string'
import Filter from './Filter'

const confirm = Modal.confirm
const Customer = ({ location, dispatch, customer, loading }) => {
  location.query = queryString.parse(location.search)
  const { countryCodeData, list, pagination, currentItem, modalVisible, modalType, selectedRowKeys, customerSelected, ChooseModalVisble } = customer
  const { pageSize } = pagination
  const modalProps = {
    item: modalType === 'create' ? {} : currentItem,
    visible: modalVisible,
    maskClosable: false,
    confirmLoading: loading.effects['customer/update'],
    title: `${modalType === 'create' ? 'Create' : 'Update'}`,
    wrapClassName: 'vertical-center-modal',
    onOk (data) {
      dispatch({
        type: `customer/${modalType}`,
        payload: data,
      })
    },
    onCancel () {
      dispatch({
        type: 'customer/hideModal',
      })
    },
  }

  const listProps = {
    dataSource: list,
    menuType: ListMenuType.MENU_UPDATE + ListMenuType.MENU_DELETE + ListMenuType.MENU_CREATE,
    loading: loading.effects['customer/list'],
    pagination,
    location,
    columnsData: [
      {
        title: 'CustomerNO',
        dataIndex: 'customerNumber',
        key: 'customerNumber',

      },
      {
        title: 'FirstName',
        dataIndex: 'firstName',
        key: 'firstName',
      },
      {
        title: 'LastName',
        dataIndex: 'lastName',
        key: 'lastName',
      },
      {
        title: 'Phone No.',
        dataIndex: 'phoneNumber',
        key: 'phoneNumber',
      },
    ],
    onChange (page) {
      const { query, pathname } = location
      dispatch(routerRedux.push({
        pathname,
        // query: {
        //   ...query,
        //   page: page.current,
        //   pageSize: page.pageSize,
        // },
        search: queryString.stringify({
          ...query,
          page: page.current,
          pageSize: page.pageSize,
        }),
      }))
    },
    onDeleteItem (id) {
      dispatch({
        type: 'customer/delete',
        payload: id,
      })
    },
    onEditItem (item) {
      dispatch(routerRedux.push({
        pathname: `customer/detail/${item.id}`,
      }))
    },
    rowSelection: {
      onChange: (keys, selectedRows) => {
        dispatch({
          type: 'customer/updateState',
          payload: {
            customerSelected: selectedRows,
            selectedRowKeys: keys,
          },
        })
      },
    },
    createTransction (id) {
      dispatch(routerRedux.push({
        pathname: `/transactionreceipt/detail/new/${id}`,
      }))
    },
  }

  const filterProps = {
    filter: {
      ...location.query,
    },
    countryCodeData,
    onFilterChange (value) {
      dispatch(routerRedux.push({
        pathname: location.pathname,
        search: queryString.stringify({
          ...value,
          page: 1,
          pageSize,
        }),
        // query: {
        //   ...value,
        //   page: 1,
        //   pageSize,
        // },

      }))
    },
    onSearch (fieldsValue) {
      fieldsValue.keyword.length ? dispatch(routerRedux.push({
        pathname: '/customer',
        query: {
          field: fieldsValue.field,
          keyword: fieldsValue.keyword,
        },
      })) : dispatch(routerRedux.push({
        pathname: '/customer',
      }))
    },
    onAdd () {
      dispatch(routerRedux.push({
        pathname: `customer/detail/${config.ADDFLAG}`,
      }))
    },
  }

  const handleDeleteItems = () => {
    dispatch({
      type: 'customer/multiDelete',
      payload: {
        ids: selectedRowKeys,
      },
    })
  }

  const handleMerage = () => {
    if (selectedRowKeys.length > 2) {
      Modal.warning({
        title: 'account Out of limit',
        content: 'The number of consolidated accounts is limited to two',
      })
    } else {
      dispatch({
        type: 'customer/updateState',
        payload: {
          ChooseModalVisble: true,
        },
      })
    }
  }
  const ChooseModalProps = {
    customerRes: customerSelected,
    title: 'Select retained customer',
    handleOk (value) {
      let customerName = ''
      for (let o of customerSelected) {
        if (o.id === value) {
          customerName = o.firstName + o.middleName + o.lastName
          break
        }
      }
      let ScrCustomerID = selectedRowKeys.filter(currentValue => currentValue !== value)
      confirm({
        title: 'Merage Confirm',
        content: `Are you sure to incorporate all account information (including phone number, address, transaction form, account balance, account details) into ${customerName}'s account`,
        onOk () {
          dispatch({
            type: 'customer/merage',
            payload: {
              location,
              dstCustomerId: value,
              scrCustomerId: ScrCustomerID[0],
            },
          })
          dispatch({
            type: 'customer/updateState',
            payload: {
              ChooseModalVisble: false,
            },
          })
        },
      })
    },
    handleCancle () {
      dispatch({
        type: 'customer/updateState',
        payload: {
          ChooseModalVisble: false,
        },
      })
    },
  }
  return (
    <Page inner>
      <Filter {...filterProps} />
      {
        selectedRowKeys.length > 0 &&
        <Row style={{ marginBottom: 24, textAlign: 'right', fontSize: 13 }}>
          <Col>
            {`Selected ${selectedRowKeys.length} items `}
            <Popconfirm title={'Are you sure delete these items?'} placement="left" onConfirm={handleDeleteItems}>
              <Button type="primary" size="large" style={{ marginLeft: 8 }}>Remove</Button>
            </Popconfirm>
            <Button type="primary" size="large" style={{ marginLeft: 8 }} onClick={handleMerage}>Merage</Button>
          </Col>
        </Row>
      }
      <List {...listProps} />
      {
        ChooseModalVisble && <ChooseModal {...ChooseModalProps} />
      }
    </Page>
  )
}

Customer.propTypes = {
  customer: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({ customer, loading }) => ({ customer, loading }))(Customer)
